package com.liuweiheng.cloud.timer;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

@Slf4j
public class QuartzManager<T extends QuartParam> {

    /**
     * 添加一个定时任务，使用默认的任务组名，触发器名，触发器组名
     */
    public static void addJob() {
        try {
            // 创建一个scheduler
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.getContext().put("skey", "svalue");

            // 创建一个Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1", "group1")
                    .usingJobData("t1", "tv1")
                    .withSchedule(
                            SimpleScheduleBuilder.simpleSchedule()
                                    .withIntervalInSeconds(3).withRepeatCount(10)
                    ).build();

            //创建一个job
            JobDetail job = JobBuilder.newJob(HelloJob.class)
                    .usingJobData("j1", "jv1")
                    .withIdentity("myjob", "mygroup").build();

            job.getJobDataMap().put("j2", "jv2");

            // 注册Trigger并启动
            scheduler.scheduleJob(job, trigger);
            scheduler.start();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 创建一个定时任务
     * @param param 参数
     * @param skey
     * @param svalue
     */
    public static void addJob(SimpleQuartParam param, String skey, String svalue) {
        try {
            /*           创建一个Scheduler            */
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.getContext().put(skey, svalue);

            /*           创建一个Trigger执行器              */
            TriggerBuilder triggerBuilder = TriggerBuilder.newTrigger();
            // 设置执行器名称、组
            triggerBuilder.withIdentity(param.getTriggerKey().getName(), param.getTriggerKey().getGroup());
            if (ObjectUtil.isNotNull(param.getTriggerMap())) {
                triggerBuilder.usingJobData(new JobDataMap(param.getTriggerMap()));
            }
            // 设置启动执行时间
            if (!param.getStartNow()) {
                triggerBuilder.startAt(param.getStartAt());
            }
            // 设置启动执行间隔
            SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
            switch (param.getIntervalType()) {
                case "Milliseconds" :
                    simpleScheduleBuilder.withIntervalInMilliseconds(param.getIntervalNum());
                    break;
                case "Seconds" :
                    simpleScheduleBuilder.withIntervalInSeconds(param.getIntervalNum());
                    break;
                case "Minutes" :
                    simpleScheduleBuilder.withIntervalInMinutes(param.getIntervalNum());
                    break;
                case "Hours" :
                    simpleScheduleBuilder.withIntervalInHours(param.getIntervalNum());
                    break;
            }
            if (param.getRepeatForever()) {
                simpleScheduleBuilder.repeatForever();
            } else {
                simpleScheduleBuilder.withRepeatCount(param.getRepeatCount());
            }
            Trigger trigger = triggerBuilder.withSchedule(simpleScheduleBuilder).build();

            /*           创建一个JobDetail              */
            JobBuilder jobBuilder = JobBuilder.newJob(param.getJobClass());
            // 设置任务名称、组
            jobBuilder.withIdentity(param.getJobKey().getName(), param.getJobKey().getGroup());
            // 存储任务中的全局变量
            if (ObjectUtil.isNotNull(param.getJobDataMap())) {
                jobBuilder.usingJobData(new JobDataMap(param.getJobDataMap()));
            }
            JobDetail jobDetail = jobBuilder.build();

            /*           启动任务              */
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建定时任务异常");
        }

    }


    public static void addJob(CronQuartParam param, String skey, String svalue) {
        try {
            /*           创建一个Scheduler            */
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.getContext().put(skey, svalue);

            /*           创建一个CronTrigger              */
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            triggerBuilder.withIdentity(param.getTriggerKey().getName(), param.getTriggerKey().getGroup());
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(param.getCronDate()));
            if (ObjectUtil.isNotNull(param.getEndTime())) {
                triggerBuilder.endAt(param.getEndTime());
            }
            Trigger trigger = triggerBuilder.build();

            /*           创建一个JobDetail              */
            JobBuilder jobBuilder = JobBuilder.newJob(param.getJobClass());
            // 设置任务名称、组
            jobBuilder.withIdentity(param.getJobKey().getName(), param.getJobKey().getGroup());
            // 存储任务中的全局变量
            if (ObjectUtil.isNotNull(param.getJobDataMap())) {
                jobBuilder.usingJobData(new JobDataMap(param.getJobDataMap()));
            }
            JobDetail jobDetail = jobBuilder.build();

            /*           启动任务              */
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建定时任务异常");
        }
    }


}
